package com.zjw.concurrency.juc.lock.reentrantLock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CinemaReadWriteLock {
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();


    private void write(){
        writeLock.lock();

        try {
            System.out.println("线程"+Thread.currentThread().getName()+"开始订票");
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放写锁");
            writeLock.unlock();
        }

    }

    private void read(){
        readLock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + "得到了读锁，正在读取");
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放读锁");
            readLock.unlock();
        }

    }

    public static void main(String[] args) {

        CinemaReadWriteLock cinemaReadWriteLock = new CinemaReadWriteLock();
//        new Thread(()->cinemaReadWriteLock.read(),"线程1").start();
//        new Thread(()->cinemaReadWriteLock.write(),"线程2").start();
//        new Thread(()->cinemaReadWriteLock.read(),"线程3").start();
//        new Thread(()->cinemaReadWriteLock.write(),"线程4").start();

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Thread(()->cinemaReadWriteLock.read(),"线程1"));
        executorService.submit(new Thread(()->cinemaReadWriteLock.write(),"线程2"));
        executorService.submit(new Thread(()->cinemaReadWriteLock.read(),"线程3"));
        executorService.submit(new Thread(()->cinemaReadWriteLock.write(),"线程4"));
    }

}
